//
//  CLVCSearchBook.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/4/16.
//

#import "CLVCSearchBook.h"
#import "CLSearchBook.h"
#import "CLHTTPClient+SearchSug.h"
#import "CLHTTPURLConfiguration.h"
#import "CLVCMain.h"
#import "CLBook.h"
#import "CLNovelView.h"
#import "CLVCNovelInfo.h"
@interface CLCellSearchBook : UITableViewCell
@property (nonatomic, strong) UILabel *lbBook;
@property (nonatomic, strong) CLSearchBook *book;
@end

@implementation CLCellSearchBook

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self configSubViews];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.lbBook.frame = self.contentView.bounds;
}

- (void)configSubViews {
    UILabel *lbBook = ({
        UILabel *view = [[UILabel alloc]initWithFrame:self.contentView.bounds];
        self.lbBook = view;
        view.textColor = [UIColor blackColor];
        view.font = [UIFont systemFontOfSize:12];
        view.textAlignment = NSTextAlignmentCenter;
        view;
    });
    [self.contentView addSubview:lbBook];
}

+ (NSString *)reuseIdentifier {
    return @"CLCellSearchBook";
}

- (void)reloadBook:(CLSearchBook *)book {
    _book = book;
    self.lbBook.text = book.title;
}
@end

@interface CLVCSearchBook ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *books;
@property (nonatomic, strong) UITextField *tfSearch;
@end

@implementation CLVCSearchBook

- (void)viewDidLoad {
    [super viewDidLoad];
    [self congfigSubViews];
    [self configRequest];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tfSearch becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}

- (void)search:(id)sender {
    self.keyWord = self.tfSearch.text;
    [self.tfSearch resignFirstResponder];
}
- (void)congfigSubViews {
    
    [self configNavigationBar];
    
    UITableView *tableView = ({
        UITableView *view = [[UITableView alloc]initWithFrame:CGRectMake(0, CL_APPLICATION_TOP_BAR_HEIGHT, self.view.width, self.view.height - CL_APPLICATION_TOP_BAR_HEIGHT) style:UITableViewStylePlain];
        self.tableView = view;
        view.delegate = self;
        view.dataSource = self;
        view.rowHeight = 45;
        [view registerClass:[CLCellSearchBook class] forCellReuseIdentifier:[CLCellSearchBook reuseIdentifier]];
        view.tableHeaderView = [[UIView alloc]init];
        view;
    });
    [self.view addSubview:tableView];
}

- (void)configNavigationBar {
    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH - 66 * 2, self.navigationController.navigationBar.height)];
    
    UITextField *tfSearch = [[UITextField alloc]initWithFrame:CGRectInset(titleView.bounds, 0, 8)];
    self.tfSearch = tfSearch;
    tfSearch.layer.borderColor = HEXRGBALPHA(0xFF0000, 0).CGColor;
    tfSearch.layer.borderWidth = 1;
    tfSearch.layer.cornerRadius = tfSearch.height/2;
    tfSearch.backgroundColor = HEXRGB(0xF8F8F8);
    tfSearch.returnKeyType = UIReturnKeyDone;
    NSInteger p = 7;
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,14 + p, 14)];
    UIImageView *ivSearch = [[UIImageView alloc]initWithFrame:CGRectMake(p, 0, 14, 14)];
    ivSearch.image = [UIImage imageNamed:@"antOutline-search"];
    [leftView addSubview:ivSearch];
    tfSearch.leftView = leftView;
    tfSearch.leftViewMode = UITextFieldViewModeAlways;
    tfSearch.delegate = self;
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentLeft;
    NSAttributedString *attributedString = [[NSAttributedString alloc]initWithString:@"书籍名称·作者·" attributes:@{NSForegroundColorAttributeName:HEXRGB(0x888888),NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:style}];
    tfSearch.attributedPlaceholder = attributedString;
    [titleView addSubview:tfSearch];
    
    self.navigationItem.titleView = titleView;
    
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(search:)];
    self.navigationItem.rightBarButtonItem = searchItem;
}

- (void)setKeyWord:(NSString *)keyWord {
    _keyWord = keyWord;
    [self configRequest];
}

- (void)configRequest {
    WEAK_SELF;
    if (NULLString(self.keyWord)) {
        return;
    }
    [SVProgressHUD showLoading];
    [[CLHTTPClient sharedInstance] searchBookWithKeyword:self.keyWord success:^(NSArray<CLSearchBook *> *books) {
        weakSelf.books = books;
        [weakSelf.tableView reloadData];
        [SVProgressHUD dismiss];
    } fail:^(NSError *error) {
        weakSelf.books = nil;
        [SVProgressHUD dismiss];
    }];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self search:nil];
    return YES;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CLCellSearchBook *cell = [tableView dequeueReusableCellWithIdentifier:[CLCellSearchBook reuseIdentifier]];
    if (!cell) {
        cell = [[CLCellSearchBook alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[CLCellSearchBook reuseIdentifier]];
    }
    CLSearchBook *book = [self.books objectAtIndex:indexPath.row];
    [cell reloadBook:book];
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.books.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CLSearchBook *book = [self.books objectAtIndex:indexPath.row];
    NSString *url = [CLHTTPURLConfiguration.sharedInstance urlSearchBookDetailWithBook:book];
    NSString *domain = [NSURL URLWithString:url].host;
    NSString *bookid = [NSString stringWithFormat:[CLBook bookidFormat],domain,book.title,book.author];
    CLBook *tocache = [[CLReadParser sharedInstance] bookById:bookid];
    if (!tocache) {
        NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
        [tmp cl_setObjectSafe:book.title forKey:@"title"];
        [tmp cl_setObjectSafe:book.author forKey:@"author"];
        [tmp cl_setObjectSafe:book.intro forKey:@"intro"];
//        [tmp cl_setObjectSafe:book.novel_book_id forKey:@"bid"];
        [tmp cl_setObjectSafe:book.cover_image forKey:@"logo"];
        [tmp cl_setObjectSafe:url forKey:@"url"];
        [tmp cl_setObjectSafe:domain forKey:@"domain"];
        [tmp cl_setObjectSafe:bookid forKey:@"bookid"];
        tocache = [[CLReadParser sharedInstance] saveToDBWithBookInfo:tmp];
    }
    NSLog(@"跳转网页:%@ - %@ %@",book.title,url,tocache.bookid);
//    UIViewController *vc = [[FlutterViewController alloc]initWithEngine:CLSharedAppDelegate.engine nibName:nil bundle:nil];
    CLVCNovelInfo *vc = [[CLVCNovelInfo alloc] initWithBook:tocache];
    [CLNavigationService pushController:vc animated:YES];
   
}

@end
